package city.spring.modules.medicalstation.drugsettings.drugsettingsDrugExt.controller;

import city.spring.modules.medicalstation.drugdepositDrugExt.entity.DrugdepositDrugExtEntity;
import city.spring.modules.medicalstation.drugdepositDrugExt.repository.DrugdepositDrugExtRepository;
import city.spring.modules.medicalstation.drugdepositDrugExt.service.DrugdepositDrugExtService;
import city.spring.modules.medicalstation.drugdepositDrugExt.vo.DrugdepositDrugVO;
import city.spring.modules.medicalstation.drugsettings.drugsettingsDrugExt.entity.DrugsettingsDrugExtEntity;
import city.spring.modules.medicalstation.drugsettings.drugsettingsDrugExt.repository.DrugsettingsDrugExtRepository;
import city.spring.modules.medicalstation.drugsettings.drugsettingsDrugExt.service.DrugsettingsDrugExtService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static city.spring.utils.UserUtils.getPrincipal;

/**
 * Controller：用药设置与药品关联表
 *
 * @author 谢金婷
 * @date 2020-10-15 09:55:17
 */
@RestController
@RequestMapping("/drugsettings/{drugsettingsId}/drug")
public class DrugsettingsDrugExtController extends ApiController {
    private final DrugsettingsDrugExtService drugsettingsDrugExtService;
    private final DrugsettingsDrugExtRepository drugsettingsDrugExtRepository;
    private final DrugdepositDrugExtService drugdepositDrugExtService;
    private final DrugdepositDrugExtRepository drugdepositDrugExtRepository;
    private final UserService userService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<DrugsettingsDrugExtEntity, ?>> entityOrderFields;

    public DrugsettingsDrugExtController(DrugsettingsDrugExtService drugsettingsDrugExtService, DrugsettingsDrugExtRepository drugsettingsDrugExtRepository, DrugdepositDrugExtService drugdepositDrugExtService, DrugdepositDrugExtRepository drugdepositDrugExtRepository, UserService userService) {
        this.drugsettingsDrugExtService = drugsettingsDrugExtService;
        this.drugsettingsDrugExtRepository = drugsettingsDrugExtRepository;
        this.drugdepositDrugExtService = drugdepositDrugExtService;
        this.drugdepositDrugExtRepository = drugdepositDrugExtRepository;
        this.userService = userService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(DrugsettingsDrugExtEntity::getId);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getDrugsettingsId);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getDrugId);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getDrugCode);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getUnit);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getTaketime);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getFrequency);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getDays);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getSetter);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getSettime);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getGmtCreate);
        entityOrderFields.add(DrugsettingsDrugExtEntity::getGmtModified);
    }

    @ModelAttribute
    public void getDrugsettingsId(@PathVariable String drugsettingsId) {
        if (drugsettingsId == null) {
            throw new RuntimeException("用药设置单ID必须不为空");
        }
        System.out.println("drugsettingsId" + drugsettingsId);
    }


    /**
     * 获取全部的 <strong>用药设置与药品关联表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DrugsettingsDrugExtEntity entity) {
        LambdaQueryChainWrapper<DrugsettingsDrugExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    //    /**
//     * 分页获取 <strong>用药设置与药品关联表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, DrugsettingsDrugExtEntity entity) {
//        LambdaQueryChainWrapper<DrugsettingsDrugExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<DrugsettingsDrugExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }
    @GetMapping
    public Object list(@PathVariable String drugsettingsId) {
        return success(drugdepositDrugExtRepository.getDrugsettingsDrugs(drugsettingsId));
    }

    //    /**
//     * 获取一个 <strong>用药设置与药品关联表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(drugsettingsDrugExtService.getById(id));
//    }
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String drugsettingsId, @PathVariable String extId) {
        return success(drugdepositDrugExtRepository.getDrugsettingsDrug(drugsettingsId, extId));
    }

    //    /**
//     * 添加一个 <strong>用药设置与药品关联表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody DrugsettingsDrugExtEntity entity) {
//        drugsettingsDrugExtService.saveDrugsettingsDrugExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }
    @PostMapping
    public Object addAll(@PathVariable String drugsettingsId, @RequestBody List<DrugdepositDrugExtEntity> drugs) {

        // 查出已有的数据
        List<DrugdepositDrugVO> dbDrugs = drugdepositDrugExtRepository.getDrugsettingsDrugs(drugsettingsId);
        // 数据库已经存在的班次列表
        Set<Integer> dbDrugIdsSet = dbDrugs.stream()
                .map(DrugdepositDrugExtEntity::getDrugId)
                .collect(Collectors.toSet());
        // 登记人（当前登录用户）
        UserEntity userEntity = userService.getUserByIdOrAccount(getPrincipal().getName());
        // 过滤掉已经存在数据库的数据
        List<DrugdepositDrugExtEntity> needSaveDrugs = drugs.stream()
                .filter(item -> {
                    if (item.getTaketime() != null || item.getFrequency() != null || item.getTimeAndQuantity() != null) {
                        item.setDrugsettingsId(drugsettingsId);
                        item.setSetter(userEntity.getId());
                        item.setSettime(new Date());
                        item.setRemainAmount(item.getTotalAmount());
                    }
                    Integer drugId = item.getDrugId();
                    // 过滤出不存在数据库中的数据
                    return drugId != null && !dbDrugIdsSet.contains(drugId);
                }).collect(Collectors.toList());
        System.out.println("needSaveDrugs" + needSaveDrugs);
        if (!needSaveDrugs.isEmpty()) {
            drugdepositDrugExtService.saveOrUpdateBatch(needSaveDrugs);
        }

        return success(null);
    }

    //    /**
//     * 修改一个 <strong>用药设置与药品关联表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody DrugsettingsDrugExtEntity entity) {
//        entity.setId(id);
//        drugsettingsDrugExtService.updateDrugsettingsDrugExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
//    @PutMapping("{extId}")
//    public Object update(@PathVariable String drugsettingsId, @PathVariable String extId, @RequestBody DrugsettingsDrugExtEntity extEntity) {
//        extEntity.setId(extId);
//        extEntity.setDrugsettingsId(drugsettingsId);
//        drugsettingsDrugExtService.updateDrugsettingsDrugExt(extEntity);
//        return success(null);
//    }
//    @PutMapping("/updateDrugdsettings/{extId}")
//    public Object updateDrugdsettings(@PathVariable String drugsettingsId, @PathVariable String extId, @RequestBody DrugdepositDrugExtEntity extEntity) {
//        System.out.println("updateDrugdsettings drugsettingsId"+drugsettingsId);
//        extEntity.setId(extId);
//        extEntity.setDrugsettingsId(drugsettingsId);
//        System.out.println("extEntity.getDrugsettingsId()"+extEntity.getDrugsettingsId());
//        drugdepositDrugExtService.saveOrUpdate(extEntity);
//        return success(null);
//    }

    /**
     * 删除一个 <strong>用药设置与药品关联表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        drugsettingsDrugExtService.deleteDrugsettingsDrugExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>用药设置与药品关联表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        drugsettingsDrugExtService.deleteDrugsettingsDrugExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DrugsettingsDrugExtEntity> buildLambdaQuery(DrugsettingsDrugExtEntity entity) {
        LambdaQueryChainWrapper<DrugsettingsDrugExtEntity> lambdaQuery = drugsettingsDrugExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DrugsettingsDrugExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDrugsettingsId()), DrugsettingsDrugExtEntity::getDrugsettingsId, entity.getDrugsettingsId());
        lambdaQuery.eq(entity.getDrugId() != null, DrugsettingsDrugExtEntity::getDrugId, entity.getDrugId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDrugCode()), DrugsettingsDrugExtEntity::getDrugCode, entity.getDrugCode());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnit()), DrugsettingsDrugExtEntity::getUnit, entity.getUnit());
        lambdaQuery.eq(entity.getTaketime() != null, DrugsettingsDrugExtEntity::getTaketime, entity.getTaketime());
        lambdaQuery.eq(entity.getFrequency() != null, DrugsettingsDrugExtEntity::getFrequency, entity.getFrequency());
        lambdaQuery.eq(entity.getDays() != null, DrugsettingsDrugExtEntity::getDays, entity.getDays());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSetter()), DrugsettingsDrugExtEntity::getSetter, entity.getSetter());
        lambdaQuery.eq(entity.getSettime() != null, DrugsettingsDrugExtEntity::getSettime, entity.getSettime());
        lambdaQuery.eq(entity.getGmtCreate() != null, DrugsettingsDrugExtEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, DrugsettingsDrugExtEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<DrugsettingsDrugExtEntity> buildQuery(DrugsettingsDrugExtEntity entity) {
        QueryWrapper<DrugsettingsDrugExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getDrugsettingsId()), "drugsettings_id", entity.getDrugsettingsId());
        wrapper.eq(entity.getDrugId() != null, "drug_id", entity.getDrugId());
        wrapper.like(StringUtils.isNotBlank(entity.getDrugCode()), "drug_code", entity.getDrugCode());
        wrapper.like(StringUtils.isNotBlank(entity.getUnit()), "unit", entity.getUnit());
        wrapper.eq(entity.getTaketime() != null, "taketime", entity.getTaketime());
        wrapper.eq(entity.getFrequency() != null, "frequency", entity.getFrequency());
        wrapper.eq(entity.getDays() != null, "days", entity.getDays());
        wrapper.like(StringUtils.isNotBlank(entity.getSetter()), "setter", entity.getSetter());
        wrapper.eq(entity.getSettime() != null, "settime", entity.getSettime());
        wrapper.eq(entity.getGmtCreate() != null, "gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
